package org.csu.mypetstoreapi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpSession;
import org.csu.mypetstoreapi.common.CommonResponse;
import org.csu.mypetstoreapi.config.CorsConfig;
import org.csu.mypetstoreapi.entity.*;
import org.csu.mypetstoreapi.persistence.*;
import org.csu.mypetstoreapi.persistence.OrderMapper;
import org.csu.mypetstoreapi.service.AccountService;
import org.csu.mypetstoreapi.service.OrderService;
import org.csu.mypetstoreapi.service.UserService;
import org.csu.mypetstoreapi.vo.AccountVO;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/order")
@CrossOrigin
//@MapperScan("org.csu.jpetstore_user.persistence")
public class OrderController {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderStatusMapper orderStatusMapper;

    @Autowired
    private LineItemMapper lineItemMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private UserService userService;


    //我的订单页面

    @GetMapping("/orderList/{username}")
    @ResponseBody
    public CommonResponse<List<Order>> orderList(@PathVariable("username") String username) {
        //查询登录用户的订单列表
        User loginUser = userService.getUserByUsername(username);
        System.out.println(loginUser.getUsername());
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("userid", loginUser.getUsername());
        List<Order> orderList = orderMapper.selectList(orderQueryWrapper);
        List<Order> orderList1 = new ArrayList<>();

        for(int i = 0;i< orderList.size();i++){
            int orderId = orderList.get(i).getOrderId();
            Order order = orderMapper.selectById(orderId);
            //把lineItems表单里的属于该Order的条目加入到Order中
            QueryWrapper<LineItem> lineItemQueryWrapper = new QueryWrapper<>();
            lineItemQueryWrapper.eq("orderid",orderId);
            List<LineItem> lineItems = lineItemMapper.selectList(lineItemQueryWrapper);

            //给lineItems中的每一条都添加上item

            for (LineItem lineItem : lineItems) {
                String itemId = lineItem.getItemId();
                //QueryWrapper每次使用都需要重新创建一次，否则还是之前的eq值
                QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
                itemQueryWrapper.eq("itemid", itemId);
                Item item = itemMapper.selectOne(itemQueryWrapper);
                lineItem.setItem(item);

                lineItem.setTotal(lineItem.getUnitPrice().multiply(new BigDecimal(lineItem.getQuantity())));
            }

            order.setLineItems(lineItems);
            orderList1.add(order);
        }

        return CommonResponse.createForSuccess(orderList1);
    }

    //查看具体订单的详细信息
    @GetMapping("/viewOrderForm/{orderId}")
    @ResponseBody
    public CommonResponse<Order> viewOrderForm(@PathVariable("orderId") int orderId) {

        Order order = orderMapper.selectById(orderId);

        //把lineItems表单里的属于该Order的条目加入到Order中
        QueryWrapper<LineItem> lineItemQueryWrapper = new QueryWrapper<>();
        lineItemQueryWrapper.eq("orderid",orderId);
        List<LineItem> lineItems = lineItemMapper.selectList(lineItemQueryWrapper);

        //给lineItems中的每一条都添加上item

        for (LineItem lineItem : lineItems) {
            String itemId = lineItem.getItemId();
            //QueryWrapper每次使用都需要重新创建一次，否则还是之前的eq值
            QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper.eq("itemid", itemId);
            Item item = itemMapper.selectOne(itemQueryWrapper);
            lineItem.setItem(item);

            lineItem.setTotal(lineItem.getUnitPrice().multiply(new BigDecimal(lineItem.getQuantity())));
        }

        order.setLineItems(lineItems);

        return CommonResponse.createForSuccess(order);
    }

    //产生新订单
    @PostMapping("/newOrderForm/{username}")
    @ResponseBody
    public CommonResponse<Order> newOrderForm(@PathVariable("username") String username, @RequestBody Cart cart) {

        Account account = accountService.getAccountByUsername(username);

        Order newOrder = new Order();
        newOrder.initOrder(account, cart);
        //数据库中orders表单中加入该订单
        //TODO:此时订单状态为未支付
        orderMapper.insert(newOrder);

        //获取数据库最新数据的订单id
        int orderId = orderMapper.getOnly();
        newOrder.setOrderId(orderId);

        System.out.println(orderId + " 新订单生成......");
        return CommonResponse.createForSuccess(newOrder);
    }
    //确认并提交订单，返回订单详情页面
    @PostMapping("/confirmOrderForm")
    @ResponseBody
    public CommonResponse<Order> confirmOrderForm(@RequestBody Order newOrder){
        int orderId = newOrder.getOrderId();

        //向lineItem表单中加入信息
        List<LineItem> lineItems = newOrder.getLineItems();
        for (int i = 0; i < lineItems.size(); i++) {
            LineItem lineItem = lineItems.get(i);
            lineItem.setOrderId(orderId);
            lineItem.setLineNumber(i + 1);
            System.out.println(lineItem.getOrderId() + " 订单item：" + (i + 1) + "成功加入lineItem表单.......");
            lineItemMapper.insert(lineItem);
        }

        //向orderStatus表单中加入信息
        //TODO:设置订单状态为已支付
        OrderStatus orderStatus = newOrder.getOrderStatus();
        orderStatus.setOrderid(orderId);
        orderStatus.setLinenum(lineItems.size());
        orderStatusMapper.insert(orderStatus);
        System.out.println(orderStatus.getOrderid() + " 订单成功加入orderStatus表单......");

        System.out.println(orderId + " 订单成功提交......");
        return CommonResponse.createForSuccess(newOrder);
    }



    //编辑订单收货地址信息
    @PostMapping("/editOrderBillAddress")
    @ResponseBody
    public CommonResponse<Order> editOrder(@RequestBody Order newOrder) {
        System.out.println("编辑订单信息......");

        int orderId = newOrder.getOrderId();
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("orderid",orderId);
        Order oldOrder = orderMapper.selectOne(orderQueryWrapper);


        orderMapper.deleteById(oldOrder);
        orderMapper.insert(newOrder);

        return CommonResponse.createForSuccess(newOrder);
    }

    @PostMapping("/setOrderDetailsToSession/{orderId}")
    @ResponseBody
    //通过orderId将订单信息放入session中
    public void setOrderDetailsToSession(HttpSession session, @PathVariable("orderId") int orderId) {

        //1、放入order实体
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("orderid", orderId);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        session.setAttribute("order", order);

        //2、放入orderStatus信息
        QueryWrapper<OrderStatus> orderStatusQueryWrapper = new QueryWrapper<>();
        orderStatusQueryWrapper.eq("orderid", orderId);
        OrderStatus orderStatus = orderStatusMapper.selectOne(orderStatusQueryWrapper);
        session.setAttribute("orderStatus", orderStatus);

        //3、放入order中的lineItems
        QueryWrapper<LineItem> lineItemQueryWrapper = new QueryWrapper<>();
        lineItemQueryWrapper.eq("orderid", orderId);

        List<LineItem> lineItems = lineItemMapper.selectList(lineItemQueryWrapper);
        //计算每个lineItem的总价
        for (int i = 0; i < lineItems.size(); i++) {
            LineItem lineItem = lineItems.get(i);
            BigDecimal total = lineItem.getUnitPrice().multiply(new BigDecimal(lineItem.getQuantity()));
            lineItem.setTotal(total);
        }
        session.setAttribute("lineItems", lineItems);

        //3、放入lineItems中包括的items
        List<Item> items = new ArrayList<>();
        QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        for (int i = 0; i < lineItems.size(); i++) {
            LineItem lineItem = lineItems.get(i);
            String itemId = lineItem.getItemId();
            itemQueryWrapper.eq("itemid", itemId);
            Item item = itemMapper.selectOne(itemQueryWrapper);
            //将productName放入item实体中
            productQueryWrapper.eq("productid", item.getProductId());
            String productName = productMapper.selectOne(productQueryWrapper).getName();
            item.setProductName(productName);

            items.add(item);
        }
        session.setAttribute("Items", items);
    }

}